package com.qf.index.gcrdo;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import com.qf.index.gcrdo.httpclient.HttpClient;
import com.qf.index.gcrdo.httpclient.HttpClientConfig;
import com.qf.index.gcrdo.httpclient.HttpClientUtil;
import com.qf.index.gcrdo.httpclient.SmallTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.BasicCookieStore;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;


@Slf4j
public class CheckDisease {

    public static void main(String[] args) throws Exception {

        // https://www.malacards.org/api/AutoCompleteApi/GetCardSuggestions post
        // https://diseases.jensenlab.org/Search?query=parkinsonism 使用这个地址
        // https://diseases.jensenlab.org/EntityQuery/
        // 检测疾病
        // 药物，数字代号：1; 基因，数字代号：2; 通路，数字代号：3; 疾病，数字代号：4
        Db use = Db.use(DSFactory.get("localdb"));
        List<Entity> query = use.query("select * from word_and_code_set_map_new where type = '疾病' and tongyi_back = '不是' and  check5 is null ");
        SmallTool.printMessError("查询到的数量："+query.size());

        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2; // 如 16
        int maxPoolSize = corePoolSize * 2; // 如 32
        long keepAliveTime = 30L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(1000000); // 缓冲突发流量
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); // 快速失败，触发降级

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, queue, handler);
        for (Entity entity : query) {
            // 这个网址目前会有防火墙 抓不了
            executor.submit(() -> {
                String word = entity.getStr("word");
                SmallTool.printMessError("开始++"+word);
//                String urlDo = "https://diseases.jensenlab.org/Search?query=parkinsonism";
                String urlDo = "https://diseases.jensenlab.org/EntityQuery/";
//                urlDo = urlDo.replace("parkinsonism", URLEncoder.encode(word));
                System.out.println(urlDo);
                String s = null;
                BasicCookieStore cookieStore = new BasicCookieStore();
                HttpClientConfig config2 = HttpClientUtil.getSearConfig(urlDo);
                Map<String,String> params = new HashMap<>();
                params.put("query", word.trim());
                params.put("section", "SEARCH");
                params.put("limit", "20");
                params.put("page", "1");
                params.put("container", "d30c0808dfa8d4def238c974ba84e195");
                config2.setProxy(true);
                try {
                    s = HttpClient.postHtml(cookieStore, params, config2);

                } catch (IOException e) {
//                    throw new RuntimeException(e);
                }
                if (StringUtil.isNotNull(s)) {
                    SmallTool.printMessError("更新成功++word+"+word);
                    if (s.contains(word)) {
                        SmallTool.printMess("匹配成功");
                    }else {
                        SmallTool.printMessError("匹配失败");
                    }
                    entity.set("check5", s);
                    try {
                        use.insertOrUpdate(entity, "id");
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                    int i = RandomUtil.randomInt(1, 3);
                    long 了 = i * 1000 + RandomUtil.randomInt(0, 1000);
                    try {
                        Thread.sleep(了);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
//                    SmallTool.printMessError("睡眠"+了+"毫秒");
                    SmallTool.printMess("__________________________________________________");
                }
            }) ;
        }
        executor.shutdown();

        // 修改后的监控逻辑
        while (!executor.isTerminated()) {
            int activeCount = executor.getActiveCount();
            long taskCount = executor.getTaskCount();
            long completedTaskCount = executor.getCompletedTaskCount();
            SmallTool.printMess("活跃线程: " + activeCount
                + " | 总任务: " + taskCount
                + " | 已完成: " + completedTaskCount
                + " | 队列剩余: " + executor.getQueue().size());

            Thread.sleep(5000);
        }
        SmallTool.printMess("线程池已完全终止");
        System.out.println("全部结束");


    }





}


